<template>
	<view class="missed-punch-container">
		<view class="form-section">
			<view class="form-title">补卡申请</view>
			
			<view class="form-item">
				<text class="form-label">补卡日期</text>
				<DateTimePicker v-model="missedDate" type="date" />
			</view>
			
			<view class="form-item">
				<text class="form-label">补卡类型</text>
				<picker @change="onTypeChange" :value="typeIndex" :range="punchTypes">
					<view class="picker-input">
						<text>{{ punchTypes[typeIndex] }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="form-label">补卡时间</text>
				<DateTimePicker v-model="missedTime" type="time" />
			</view>
			
			<view class="form-item">
				<text class="form-label">关联项目 <text class="required">*</text></text>
				<picker @change="onProjectChange" :value="projectIndex" :range="projectList">
					<view class="picker-input">
						<text>{{ projectList[projectIndex] }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
			
			<view class="form-item textarea-item">
				<text class="form-label">补卡原因</text>
				<textarea class="form-textarea" v-model="reason" placeholder="请详细说明补卡原因" maxlength="200"></textarea>
				<text class="char-count">{{ reason.length }}/200</text>
			</view>
			
			<view class="form-item upload-item">
				<view class="upload-header">
					<text class="form-label">说明附件</text>
					<view class="upload-button" @tap="uploadFile">
						<text class="upload-icon">+</text>
					</view>
				</view>
				<view class="upload-section">
					<view class="upload-list" v-if="uploadedFiles.length > 0">
						<view class="upload-item-file" v-for="(file, index) in uploadedFiles" :key="index">
							<image class="file-icon" :src="file.url" mode="aspectFit"></image>
							<text class="file-name">{{ file.name }}</text>
							<text class="file-size">{{ file.size }}</text>
							<text class="file-delete" @tap="deleteFile(index)">×</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 审批流程 -->
		<view class="approval-section">
			<text class="section-title">审批流程</text>
			<view class="approval-steps">
				<view class="approval-step" v-for="(step, index) in approvalSteps" :key="index">
					<view class="step-header">
						<view class="step-avatar">
							<text class="avatar-text">{{ step.user_name.charAt(0) }}</text>
						</view>
						<view class="step-info">
							<text class="step-name">{{ step.user_name }}</text>
							<text class="step-position">{{ step.position }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-section">
			<button class="submit-button" @tap="submitApplication" :disabled="!canSubmit()">
				提交
			</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import DateTimePicker from '@/components/DateTimePicker.vue'
import { attendanceApi } from '@/common/api'
import { getProjects, getCurrentToken } from '@/common/auth'
import config from '@/common/config'
import { uploadAttachments, formatFileSize } from '@/common/upload'

// TypeScript interfaces
interface MissedPunchFile {
	name: string
	url: string
	path: string
	size: string
	type: string
}

interface ApprovalStep {
	position: string
	user_name: string
	user_id: string
	status?: string
	comment?: string
	update_time?: string
}

interface Project {
	project_id: string
	project_name: string
}

// 表单数据
const missedDate = ref<string>('')
const missedTime = ref<string>('')
const reason = ref<string>('')
const uploadedFiles = ref<MissedPunchFile[]>([])
const punchTypes = ref<string[]>(['上班打卡', '下班打卡'])
const typeIndex = ref<number>(0)
const workflow_id = ref<number>(0)
const region_company = ref<string>('')

// 项目相关
const projects = getProjects() as Project[]
const projectIndex = ref<number>(0)
const projectList = ref<string[]>(projects.map((project) => project.project_name))

// 审批流程
const approvalSteps = ref<ApprovalStep[]>([])

// 类型变更处理
const onTypeChange = (e: any) => {
	typeIndex.value = e.detail.value
}

// 项目变更处理
const onProjectChange = (e: any) => {
	projectIndex.value = e.detail.value
	// 重新加载审批人
	loadApprovers()
}

// 上传文件
const uploadFile = () => {
	uni.chooseImage({
		count: 1,
		sourceType: ['album', 'camera'],
		extension: ['jpg', 'jpeg', 'png'],
		success: (res: any) => {
			const filePath = res.tempFilePaths[0]
			const extension = filePath.toLowerCase().split('.').pop()
			const fileName = `附件${uploadedFiles.value.length + 1}.${extension}`

			// 根据平台获取文件大小
			// #ifdef H5
			// H5环境下，从chooseImage的返回结果中获取文件信息
			const tempFile = res.tempFiles && res.tempFiles[0]
			const fileSize = tempFile ? tempFile.size : 0

			console.log((fileName))
			uploadedFiles.value.push({
				name: fileName,
				url: filePath, // 保存临时文件路径用于预览
				path: filePath, // 保存文件路径用于上传
				size: formatFileSize(fileSize),
				type: extension
			})
			// #endif

			// #ifndef H5
			// 非H5环境下使用文件系统管理器
			console.log("非H5环境")
			uni.getFileSystemManager().getFileInfo({
				filePath: filePath,
				success: (fileInfo: any) => {
					uploadedFiles.value.push({
						name: fileName,
						url: filePath,
						path: filePath,
						size: formatFileSize(fileInfo.size),
						type: extension
					})
				},
				fail: (error: any) => {
					console.error('获取文件信息失败:', error)
					uploadedFiles.value.push({
						name: fileName,
						url: filePath,
						path: filePath,
						size: '未知大小',
						type: extension
					})
				}
			})
			// #endif
		},
		fail: (error: any) => {
			console.error('选择图片失败:', error)
			uni.showToast({
				title: '选择图片失败',
				icon: 'none'
			})
		}
	})
}

// 删除文件
const deleteFile = (index: number) => {
	uploadedFiles.value.splice(index, 1)
}

// 是否可以提交
const canSubmit = (): boolean => {
	return !!missedDate.value && !!missedTime.value && !!reason.value
}

// 加载审批人列表
const loadApprovers = async () => {
	try {
		if (projects[projectIndex.value]) {
			uni.showLoading({
				title: '加载审批人...'
			})
			const projectId = projects[projectIndex.value].project_id
			const res = await attendanceApi.getApprovers(projectId)
			uni.hideLoading()

			if (res.success && res.data.length > 0) {
				const approvalWorkflow = res.data[0]
				workflow_id.value = approvalWorkflow.id
				region_company.value = approvalWorkflow.region_company
				approvalSteps.value = approvalWorkflow.approvers.map((approver: any) => ({
					position: approver.approver_user.position || '审批人',
					user_name: approver.approver_user.name,
					user_id: approver.approver_user_id
				}))
				console.log('审批人列表加载成功:', approvalSteps.value)
			} else {
				// 使用默认审批流程
				approvalSteps.value = [
					{
						position: '直接主管',
						user_name: '主管',
						user_id: '0'
					},
					{
						position: '人事专员',
						user_name: '人事',
						user_id: '0'
					}
				]
				console.log('使用默认审批人列表')
			}
		}
	} catch (error) {
		uni.hideLoading()
		console.error('获取审批人列表失败:', error)
		
		uni.showToast({
			title: '获取审批人失败，使用默认配置',
			icon: 'none',
			duration: 2000
		})
		
		// 使用默认审批流程
		approvalSteps.value = [
			{
				position: '直接主管',
				user_name: '主管',
				user_id: '0'
			},
			{
				position: '人事专员',
				user_name: '人事',
				user_id: '0'
			}
		]
	}
}

// 提交申请
const submitApplication = async () => {
	if (!canSubmit()) {
		uni.showToast({
			title: '请完善申请信息',
			icon: 'none'
		})
		return
	}

	uni.showLoading({
		title: '提交中...'
	})

	try {
		// 准备提交的数据（先不包含附件）
		const punchDate = new Date(missedDate.value)
		const [hours, minutes] = missedTime.value.split(':').map(Number)
		punchDate.setHours(hours, minutes, 0, 0)
		
		const submitData = {
			punchType: punchTypes.value[typeIndex.value] === '上班打卡' ? 'check_in' : 'check_out',
			punchTime: punchDate.toISOString(),
			reason: reason.value,
			submitTime: new Date().toISOString(),
			region_company: region_company.value,
			workflow_id: workflow_id.value,
			project_id: projects[projectIndex.value].project_id
		}

		console.log('提交的补卡数据:', submitData)

		uni.showLoading({
			title: '提交申请中...'
		})

		// 先提交表单数据
		const res = await attendanceApi.applyMissedPunch(submitData)

		if (!res.success) {
			uni.hideLoading()
			uni.showToast({
				title: res.message || '提交失败',
				icon: 'none',
				duration: 3000
			})
			return
		}

		// 获取申请ID
		const { missed_punch_id, approval_instance_id } = res.data

		// 如果有附件，再上传附件
		if (uploadedFiles.value.length > 0) {
			uni.showLoading({
				title: '上传附件中...'
			})

			try {
				// 转换文件格式
				const files = uploadedFiles.value.map(file => ({
					path: file.path,
					name: file.name,
					size: parseInt(file.size) || 0,
					type: file.type
				}));

				// 使用通用上传工具上传文件，支持并行上传
				const uploadedAttachments = await uploadAttachments(				
					files,
					true, // 并行上传
					{
						type: "attachment",
						relation_id: missed_punch_id, // 传递申请ID
						approval_instance_id: approval_instance_id, // 传递审批实例ID
						relation_type: "missed_punch" // 传递申请类型
					},
					(current, total) => {
						// 更新上传进度
						uni.showLoading({
							title: `上传中 ${current}/${total}`
						});
					}
				);

				// 如果需要，可以调用更新附件API
				if (uploadedAttachments.length > 0) {
					const attachments = uploadedAttachments.map(file => ({
						path: file.path,
						size: String(file.size),
						type: file.type,
						url: file.url
					}));

					// 可选：调用更新附件API
					// await attendanceApi.updateAttachments(missed_punch_id, attachments);
				}
			} catch (error: any) {
				console.error('文件上传失败:', error)
				uni.showToast({
					title: '部分附件上传失败，请在详情页重新上传',
					icon: 'none',
					duration: 2000
				})
				// 继续流程，不影响已提交的申请
			}
		}

		uni.hideLoading()
		console.log('提交成功:', res)

		uni.showToast({
			title: '申请提交成功',
			icon: 'success'
		})

		// 清空表单
		missedDate.value = ''
		missedTime.value = ''
		reason.value = ''
		uploadedFiles.value = []
		typeIndex.value = 0

		// 返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	} catch (error: any) {
		uni.hideLoading()
		console.error('提交失败:', error)
		uni.showToast({
			title: error.message || '网络错误，请稍后重试',
			icon: 'none',
			duration: 3000
		})
	}
}

// 页面加载时初始化
onLoad(() => {
	// 设置默认日期为今天
	const today = new Date()
	const year = today.getFullYear()
	const month = String(today.getMonth() + 1).padStart(2, '0')
	const day = String(today.getDate()).padStart(2, '0')
	missedDate.value = `${year}-${month}-${day}`
	
	// 设置默认时间
	const hours = String(today.getHours()).padStart(2, '0')
	const minutes = String(today.getMinutes()).padStart(2, '0')
	missedTime.value = `${hours}:${minutes}`
	
	// 加载审批人
	loadApprovers()
})
</script>

<style scoped>
.missed-punch-container {
	padding: 0;
	background-color: #f5f6fa;
	min-height: 100vh;
}

.form-section {
	background: white;
	border-radius: 0;
	padding: 0;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.form-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	padding: 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-item {
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
	margin-bottom: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	min-height: 88rpx;
}

.form-item:last-child {
	border-bottom: none;
}

.form-item.textarea-item {
	flex-direction: column;
	align-items: stretch;
	min-height: auto;
}

.form-item.upload-item {
	flex-direction: column;
	align-items: stretch;
	min-height: auto;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 0;
	display: block;
	flex-shrink: 0;
}

.required {
	color: #f44336;
	font-size: 28rpx;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	min-height: 48rpx;
	flex: 1;
	max-width: 400rpx;
}

.picker-arrow {
	color: #999;
	margin-left: 8rpx;
}

.form-textarea {
	width: 100%;
	box-sizing: border-box;
	min-height: 120rpx;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	font-size: 28rpx;
	line-height: 1.5;
	margin-top: 16rpx;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
	display: block;
}

.upload-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.upload-section {
	border: none;
	border-radius: 0;
	padding: 0;
	margin-top: 0;
}

.upload-list {
	margin-bottom: 0;
}

.upload-item-file {
	display: flex;
	align-items: center;
	padding: 16rpx 0;
	background: transparent;
	border-radius: 0;
	margin-bottom: 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.upload-item-file:last-child {
	border-bottom: none;
}

.file-icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 16rpx;
	background: #ddd;
	border-radius: 8rpx;
}

.file-name {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.file-size {
	font-size: 24rpx;
	color: #999;
	margin-right: 16rpx;
}

.file-delete {
	font-size: 36rpx;
	color: #ccc;
	font-weight: normal;
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: transparent;
	border-radius: 50%;
	border: none;
}

.upload-button {
	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box;
	border-radius: 50%;
	background: #f8f9fa;
	width: 42rpx;
	height: 42rpx;
	border: 2rpx solid #e0e0e0;
	margin-top: 0;
}

.upload-icon {
	font-size: 24rpx;
	color: #999;
	line-height: 38rpx;
}

.approval-section {
	background: white;
	border-radius: 0;
	padding: 32rpx;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.approval-steps {
	margin-top: 24rpx;
}

.approval-step {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
}

.step-header {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.step-avatar {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #2B5BA1;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
	margin-right: 16rpx;
}

.avatar-text {
	color: white;
}

.step-info {
	flex: 1;
}

.step-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
}

.step-position {
	font-size: 24rpx;
	color: #666;
}

.submit-section {
	padding: 32rpx;
	margin-bottom: 0;
}

.submit-button {
	width: 100%;
	background: #2B5BA1;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 24rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.submit-button[disabled] {
	background: #ccc;
}
</style> 